package com.caption.jdk.stream;

import com.caption.jdk.lambda.Person;

import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * collection 进行聚合操作、 求最大值、最小值 平均值、个数
 */
public class TestStream05 {
    public static void main(String[] args) {
        //求最大值
        Optional<Person> max = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25)).collect(Collectors.maxBy((p1, p2) -> p1.getAge() - p2.getAge()));
        System.out.println("最大年龄="+max.get());
        //求最小值
        Optional<Person> min = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25)).collect(Collectors.minBy((p1, p2) -> p1.getAge() - p2.getAge()));
        System.out.println("最小年龄="+min.get());
        //求和
        Integer sum = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25)).collect(Collectors.summingInt(Person::getAge));
        System.out.println("年龄的求和="+sum);
        //平均值
        double avg = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25)).collect(Collectors.averagingDouble(Person::getAge));
        System.out.println("平均值="+avg);

        //统计个数
        Long count = Stream.of(new Person("张三", 20),
                new Person("李四", 30),
                new Person("王五", 25)).collect(Collectors.counting());
        System.out.println("总数="+count);


    }
}
